<template>
    <div class="product-detail">
        <NavigationBar />

        <div v-if="loading" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载商品详情中...</p>
        </div>

        <div v-else-if="!product" class="not-found">
            <h2>商品未找到</h2>
            <button @click="goBack" class="back-button">返回商品列表</button>
        </div>

        <div v-else class="detail-container">
            <!-- 返回按钮 -->
            <button class="back-button" @click="goBack">
                &larr; 返回产品列表
            </button>

            <div class="product-main">
                <!-- 产品图片区域 -->
                <div class="product-gallery">
                    <div class="main-image">
                        <img :src="product.image || placeholderImage" :alt="product.name" />
                    </div>
                    <div class="thumbnails" v-if="product.images && product.images.length">
                        <div v-for="(img, index) in product.images" :key="index" class="thumbnail"
                            :class="{ active: currentImage === index }" @click="currentImage = index">
                            <img :src="img || placeholderImage" :alt="`${product.name}-${index}`" />
                        </div>
                    </div>
                </div>

                <!-- 产品信息区域 -->
                <div class="product-content">
                    <h1>{{ product.name }}</h1>

                    <div class="meta-info">
                        <div class="rating">
                            <span v-for="star in 5" :key="star" class="star"
                                :class="{ 'filled': star <= product.rating }">★</span>
                            <span class="review-count">({{ product.reviews }}条评价)</span>
                        </div>

                        <div class="sku">商品编号: {{ product.id }}</div>
                        <div class="category">分类: {{ product.category }}</div>
                    </div>

                    <div class="price-section">
                        <span class="current-price">￥{{ calculateDiscountPrice(product) }}</span>
                        <span v-if="product.discount" class="original-price">￥{{ product.price.toFixed(2) }}</span>
                        <span v-if="product.discount" class="discount-badge">-{{ product.discount }}%</span>
                    </div>

                    <div class="product-description">
                        <h3>产品描述</h3>
                        <p>{{ product.description }}</p>
                        <div v-if="product.details" class="product-details">
                            <h3>产品详情</h3>
                            <ul>
                                <li v-for="(detail, index) in product.details" :key="index">{{ detail }}</li>
                            </ul>
                        </div>
                    </div>

                    <div class="quantity-selector">
                        <label>数量:</label>
                        <div class="quantity-controls">
                            <button @click="decrementQuantity">-</button>
                            <input type="number" v-model.number="quantity" min="1" @change="validateQuantity" />
                            <button @click="incrementQuantity">+</button>
                        </div>
                    </div>

                    <div class="action-buttons">
                        <button class="add-to-cart-btn" @click="addToCart">
                            加入购物车
                        </button>
                        <button class="buy-now-btn" @click="buyNow">
                            立即购买
                        </button>

                        <transition name="fade">
                            <div v-if="showAddSuccess" class="add-success-message">
                                ✓ 已添加到购物车 ({{ quantity }}件)
                            </div>
                        </transition>
                    </div>
                </div>
            </div>

            <!-- 产品评价区域 -->
            <div class="product-reviews" v-if="product.reviewsList && product.reviewsList.length">
                <h2>用户评价 ({{ product.reviews }})</h2>
                <div class="review-list">
                    <div v-for="review in product.reviewsList" :key="review.id" class="review-item">
                        <div class="review-header">
                            <span class="user-name">{{ review.user }}</span>
                            <div class="review-rating">
                                <span v-for="star in 5" :key="star" class="star"
                                    :class="{ 'filled': star <= review.rating }">★</span>
                            </div>
                            <span class="review-date">{{ review.date }}</span>
                        </div>
                        <p class="review-content">{{ review.content }}</p>
                    </div>
                </div>
            </div>
        </div>

        <Footer />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import NavigationBar from '@/components/NavigationBar.vue'
import Footer from '@/components/Footer.vue'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const showAddSuccess = ref(false);

// 商品数据状态
const product = ref(null)
const loading = ref(true)
const currentImage = ref(0)

// 占位图
const placeholderImage = 'https://via.placeholder.com/400x400?text=No+Image'

// 模拟从API获取所有商品数据
const fetchProductDetails = (id) => {
    // 实际项目中这里应该是API请求
    const allProducts = [
        {
            id: 1,
            name: '天然豆腐猫砂',
            description: '环保可冲厕所，强力结团除臭，天然无尘配方，适合敏感猫咪',
            price: 69.9,
            discount: 15,
            image: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcbu01.alicdn.com%2Fimg%2Fibank%2FO1CN01U6ERvv1yUbkNGQoi3_%21%212208134376582-0-cib.jpg&refer=http%3A%2F%2Fcbu01.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1746876398&t=96c32d4a1cff0b7543c26dd3a381a9f7',
            rating: 4,
            reviews: 128,
            isNew: false,
            category: '猫用品',
            details: [
                '材质: 天然豆腐渣',
                '净含量: 6L/袋',
                '适用对象: 全年龄段猫咪',
                '除臭效果: 强效除臭',
                '结团性能: 快速结团',
                '特点: 环保可冲，无尘，低过敏'
            ],
            reviewsList: [
                {
                    id: 1,
                    user: '猫奴小张',
                    rating: 5,
                    date: '2023-05-15',
                    content: '非常好用的猫砂，结团快，几乎没有灰尘，猫咪很喜欢'
                },
                {
                    id: 2,
                    user: '爱宠人士',
                    rating: 4,
                    date: '2023-04-22',
                    content: '性价比很高，除臭效果不错，会继续回购'
                },
                {
                    id: 3,
                    user: '猫咪妈妈',
                    rating: 5,
                    date: '2023-07-01',
                    content: '猫咪用得很开心，结团效果超棒，推荐购买！'
                }
            ]
        },
        {
            id: 2,
            name: '全价无谷狗粮',
            description: '含三文鱼配方，促进毛发亮泽',
            price: 159,
            discount: 20,
            image: 'https://img14.360buyimg.com/pop/jfs/t1/6818/40/23534/109423/64f827c6F24fb9ee0/efb12d5dc659f080.jpg',
            rating: 5,
            reviews: 256,
            isNew: true,
            category: '狗粮',
            details: [
                '主要成分: 三文鱼、红薯、豌豆',
                '净含量: 5kg',
                '适用对象: 全年龄段狗狗',
                '特点: 无谷物配方，低敏，易消化'
            ],
            reviewsList: [
                {
                    id: 1,
                    user: '狗狗家长',
                    rating: 5,
                    date: '2023-06-10',
                    content: '狗狗很爱吃，毛发确实变得有光泽了'
                },
                {
                    id: 2,
                    user: '宠物爱好者',
                    rating: 5,
                    date: '2023-05-20',
                    content: '狗狗吃得香，身体更健康了，推荐！'
                },
                {
                    id: 3,
                    user: '狗狗爸爸',
                    rating: 4,
                    date: '2023-07-05',
                    content: '性价比很高，狗狗很喜欢，会继续购买'
                }
            ]
        },
        {
            id: 3,
            name: '智能饮水机',
            description: '静音循环，保持水源新鲜',
            price: 199,
            discount: 10,
            image: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fbao%2Fuploaded%2Fi2%2F3078263620%2FO1CN01jCQfma1cc0bAkRLsK_%21%210-item_pic.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1746877086&t=95b92aa98f7677082645b959f41371b4%212206688630784-0-cib.jpg&refer=http%3A%2F%2Fcbu01.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1746877229&t=cd9603aaf22dd2df2d78e7c19d111a6chttps://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcbu01.alicdn.com%2Fimg%2Fibank%2FO1CN01RUFBJx1Hf7NNKBmea_%21',
            rating: 4,
            reviews: 87,
            isNew: false,
            category: '宠物电器',
            details: [
                '材质: 食品级塑料',
                '容量: 3L',
                '适用对象: 猫狗通用',
                '特点: 静音设计，自动循环过滤'
            ],
            reviewsList: [
                {
                    id: 1,
                    user: '狗狗家长',
                    rating: 5,
                    date: '2023-06-10',
                    content: '狗狗更爱喝水了'
                },
                {
                    id: 2,
                    user: '猫咪家长',
                    rating: 4,
                    date: '2023-05-18',
                    content: '猫咪喝水更方便了，机器也很安静'
                },
                {
                    id: 3,
                    user: '宠物主人',
                    rating: 5,
                    date: '2023-07-03',
                    content: '水质保持得很好，宠物喝水更健康'
                }
            ]
        },
        {
            id: 4,
            name: '豪华猫爬架',
            description: '多层设计，天然剑麻柱',
            price: 399,
            discount: 0,
            image: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcbu01.alicdn.com%2Fimg%2Fibank%2F2017%2F488%2F447%2F4215744884_206345325.jpg&refer=http%3A%2F%2Fcbu01.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1746889154&t=dee5fe9a94179b76f1a5d82ab58535d7',
            rating: 5,
            reviews: 42,
            isNew: true,
            category: '猫家具',
            details: [
                '材质: 木材、剑麻、毛毯',
                '尺寸: 120cm x 60cm x 180cm',
                '适用对象: 猫咪',
                '特点: 多层设计，满足猫咪攀爬、抓挠需求'
            ],
            reviewsList: [
                {
                    id: 1,
                    user: '猫猫家长',
                    rating: 5,
                    date: '2023-06-10',
                    content: '猫猫很爱玩'
                },
                {
                    id: 2,
                    user: '猫咪爱好者',
                    rating: 5,
                    date: '2023-05-25',
                    content: '猫爬架质量很好，猫咪很喜欢'
                },
                {
                    id: 3,
                    user: '猫咪主人',
                    rating: 4,
                    date: '2023-07-01',
                    content: '很实用，猫咪每天都在上面玩耍'
                }
            ]
        },
        {
            id: 5,
            name: '宠物美容梳',
            description: '防静电，去除浮毛',
            price: 45,
            discount: 5,
            image: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcbu01.alicdn.com%2Fimg%2Fibank%2FO1CN01eunaW61hMxdwrsZOv_%21%212209290504264-0-cib.jpg&refer=http%3A%2F%2Fcbu01.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1746877306&t=bd18b9ccea1ee60e3480d19f215f0e54',
            rating: 4,
            reviews: 193,
            isNew: false,
            category: '美容用品',
            details: [
                '材质: 优质塑料',
                '尺寸: 20cm x 7cm',
                '适用对象: 猫狗通用',
                '特点: 防静电设计，轻松去除浮毛'
            ],
            reviewsList: [
                {
                    id: 1,
                    user: '猫猫家长',
                    rating: 5,
                    date: '2023-06-10',
                    content: '能把废毛轻松弄下，不用担心孩子吞毛了'
                },
                {
                    id: 2,
                    user: '宠物美容师',
                    rating: 5,
                    date: '2023-05-30',
                    content: '非常好用，对宠物毛发很温和'
                },
                {
                    id: 3,
                    user: '狗狗家长',
                    rating: 4,
                    date: '2023-07-02',
                    content: '狗狗很喜欢，毛发更顺滑了'
                }
            ]
        },
        {
            id: 6,
            name: '自动喂食器',
            description: 'APP控制，定时定量投喂',
            price: 299,
            discount: 25,
            image: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcbu01.alicdn.com%2Fimg%2Fibank%2FO1CN01qK6yDc1ZL7BJMqqTb_%21%213823753177-0-cib.jpg&refer=http%3A%2F%2Fcbu01.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1746877446&t=e027922c49fd721effff4b5f655128ff',
            rating: 4,
            reviews: 76,
            isNew: false,
            category: '宠物电器',
            details: [
                '材质: 食品级塑料',
                '容量: 5L',
                '适用对象: 猫狗通用',
                '特点: APP控制，定时定量投喂'
            ],
            reviewsList: [
                {
                    id: 1,
                    user: '狗狗家长',
                    rating: 5,
                    date: '2023-06-10',
                    content: '定点就放量，猫猫天天蹲着，再也不用我早起放量了'
                },
                {
                    id: 2,
                    user: '宠物主人',
                    rating: 5,
                    date: '2023-05-28',
                    content: '很方便，出差也可以照顾宠物'
                },
                {
                    id: 3,
                    user: '猫咪家长',
                    rating: 4,
                    date: '2023-07-04',
                    content: '操作简单，宠物很喜欢'
                }
            ]
        }
    ];

    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(allProducts.find(p => p.id === id))
        }, 500) // 模拟网络延迟
    })
}

// 计算折扣价格
const calculateDiscountPrice = (product) => {
    return product.discount
        ? (product.price * (1 - product.discount / 100)).toFixed(2)
        : product.price.toFixed(2)
}

// 数量操作
const quantity = ref(1);

const incrementQuantity = () => {
    quantity.value++;
};

const decrementQuantity = () => {
    if (quantity.value > 1) {
        quantity.value--;
    }
};

const validateQuantity = () => {
    if (quantity.value < 1) {
        quantity.value = 1
    }
}

// 加入购物车逻辑
const addToCart = () => {
    if (!product.value) return;

    cartStore.addToCart({
        ...product.value,
        quantity: quantity.value
    });

    showAddSuccess.value = true;
    setTimeout(() => {
        showAddSuccess.value = false;
    }, 3000);

    // 重置数量
    quantity.value = 1;
};

const buyNow = () => {
    addToCart();
    router.push('/shopping-cart');
};

// 返回上一页
const goBack = () => {
    router.go(-1)
}


// 初始化加载商品数据
onMounted(async () => {
    try {
        const id = parseInt(route.params.id)
        if (isNaN(id)) {
            throw new Error('无效的商品ID')
        }

        const data = await fetchProductDetails(id)
        if (!data) {
            throw new Error('商品未找到')
        }

        product.value = data
    } catch (error) {
        console.error('加载商品详情失败:', error)
        router.push('/pet-products')
    } finally {
        loading.value = false
    }
})
</script>

<style scoped>
.product-detail {
    background-color: #f9f5f0;
    min-height: 100vh;
}

.detail-container {

    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
}

.back-button {
    background: none;
    background-color: #f7edcf;
    border: none;
    color: #8b7355;
    font-size: 1rem;
    cursor: pointer;
    margin-bottom: 1rem;
    padding: 0.5rem 0;
}

/* 添加成功提示样式 */
.add-success-message {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: #42b983;
    color: white;
    padding: 10px 20px;
    border-radius: 4px;
    animation: fadeInOut 3s ease-in-out;
    opacity: 0;
}

@keyframes fadeInOut {
    0% {
        opacity: 0;
        transform: translateY(10px);
    }

    20% {
        opacity: 1;
        transform: translateY(0);
    }

    80% {
        opacity: 1;
        transform: translateY(0);
    }

    100% {
        opacity: 0;
        transform: translateY(10px);
    }
}

/* 数量选择器样式 */
.quantity-controls {
    display: flex;
    align-items: center;
    margin: 10px 0;
}

.quantity-controls button {
    width: 30px;
    height: 30px;
    background: #f5f5f5;
    border: 1px solid #ddd;
    cursor: pointer;
    font-size: 16px;
}

.quantity-controls input {
    width: 50px;
    height: 30px;
    text-align: center;
    margin: 0 5px;
    border: 1px solid #ddd;
}

/* 按钮样式 */
.action-buttons {
    display: flex;
    gap: 15px;
    margin-top: 20px;
}

.add-to-cart-btn,
.buy-now-btn {
    padding: 12px 24px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: bold;
    transition: all 0.3s;
}

.add-to-cart-btn {
    background: #f0c14b;
    color: #111;
}

.add-to-cart-btn:hover {
    background: #ddb347;
}

.buy-now-btn {
    background: #42b983;
    color: white;
}

.buy-now-btn:hover {
    background: #3aa876;
}

.back-button:hover {
    text-decoration: underline;
}

.product-main {
    display: flex;
    gap: 3rem;
    margin-bottom: 3rem;
}

.product-gallery {
    flex: 1;
}

.main-image {
    width: 100%;
    height: 500px;
    background-color: white;
    border-radius: 10px;
    overflow: hidden;
    margin-bottom: 1rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.main-image img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.thumbnails {
    display: flex;
    gap: 1rem;
}

.thumbnail {
    width: 80px;
    height: 80px;
    border: 2px solid transparent;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    background-color: white;
}

.thumbnail.active {
    border-color: #d4a373;
}

.thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-content {
    flex: 1;
}

.product-content h1 {
    color: #5a4a42;
    margin-top: 0;
    margin-bottom: 1rem;
}

.meta-info {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 1.5rem;
    color: #8e8c84;
    font-size: 0.9rem;
}

.rating {
    display: flex;
    align-items: center;
}

.star {
    color: #e0e0e0;
    font-size: 1rem;
}

.star.filled {
    color: #ffc107;
}

.review-count {
    margin-left: 0.5rem;
}

.price-section {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.current-price {
    font-size: 1.8rem;
    font-weight: bold;
    color: #b5838d;
}

.original-price {
    font-size: 1.2rem;
    color: #a5a5a5;
    text-decoration: line-through;
}

.discount-badge {
    background-color: #cb997e;
    color: white;
    padding: 0.3rem 0.6rem;
    border-radius: 4px;
    font-size: 0.9rem;
    font-weight: bold;
}

.product-description {
    margin-bottom: 2rem;
    line-height: 1.6;
}

.product-description h3 {
    color: #5a4a42;
    margin-bottom: 0.5rem;
}

.product-details {
    margin-top: 1.5rem;
}

.product-details ul {
    padding-left: 1.5rem;
}

.product-details li {
    margin-bottom: 0.5rem;
}

.quantity-selector {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 2rem;
}

.quantity-controls {
    display: flex;
    align-items: center;
}

.quantity-controls button {
    width: 40px;
    height: 40px;
    font-size: 1.2rem;
    background-color: #f0f0f0;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.quantity-controls input {
    width: 60px;
    height: 40px;
    text-align: center;
    margin: 0 0.5rem;
    border: 1px solid #ddd;
    border-radius: 5px;
    font-size: 1.1rem;
}

.action-buttons {
    display: flex;
    gap: 1rem;
}

.add-to-cart-btn,
.buy-now-btn {
    flex: 1;
    padding: 1rem;
    font-size: 1.1rem;
    font-weight: bold;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.add-to-cart-btn {
    background-color: #d4a373;
    color: white;
}

.add-to-cart-btn:hover {
    background-color: #cb997e;
}

.buy-now-btn {
    background-color: #5a4a42;
    color: white;
}

.buy-now-btn:hover {
    background-color: #3a2e28;
}

.product-reviews {
    background-color: white;
    padding: 2rem;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.product-reviews h2 {
    color: #5a4a42;
    margin-top: 0;
    margin-bottom: 1.5rem;
}

.review-item {
    padding: 1.5rem 0;
    border-bottom: 1px solid #f0f0f0;
}

.review-item:last-child {
    border-bottom: none;
}

.review-header {
    display: flex;
    align-items: center;
    margin-bottom: 0.5rem;
    flex-wrap: wrap;
    gap: 0.5rem 1rem;
}

.user-name {
    font-weight: bold;
    color: #5a4a42;
}

.review-rating {
    display: flex;
}

.review-date {
    color: #8e8c84;
    font-size: 0.9rem;
}

.review-content {
    margin: 0;
    line-height: 1.6;
}

@media (max-width: 768px) {
    .product-main {
        flex-direction: column;
    }

    .main-image {
        height: 350px;
    }

    .action-buttons {
        flex-direction: column;
    }
}
</style>